/*
 * @Author: pardon110
 * @Date: 2024-03-17 17:14:50
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-18 09:01:50
 * @FilePath: \days7\web\group\grp\engine.go
 * @Description:  e ->
 */
package grp

import "net/http"

type HandlerFunc func(*Context)

type (
	RouterGroup struct {
		prefix string
		engine *Engine // all groups share a Engine !!!
	}

	Engine struct {
		*RouterGroup // 嵌套导出字段，其verb方法向上转发
		router       *router
		groups       []*RouterGroup // store all groups
	}
)

func New() *Engine {
	engine := &Engine{router: newRouter()}
	engine.RouterGroup = &RouterGroup{engine: engine}
	engine.groups = []*RouterGroup{engine.RouterGroup}
	return engine
}

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c := newContext(w, r) // 并发安全，每次请求新构建一个上下文
	e.router.handle(c)
}

func (e *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, e)
}

// Group 创建一个新的分组实例
// 所有分组实例共享同一个 Engine 实例
func (g *RouterGroup) Group(prefix string) *RouterGroup {
	e := g.engine
	newGroup := &RouterGroup{
		prefix: g.prefix + prefix,
		engine: e,
	}
	// 记录所有的分组路径
	e.groups = append(e.groups, newGroup)
	return newGroup
}

func (g *RouterGroup) addRoute(method string, comp string, handler HandlerFunc) {
	pattern := g.prefix + comp
	g.engine.router.addRoute(method, pattern, handler)
}

func (g *RouterGroup) GET(pattern string, handler HandlerFunc) {
	g.addRoute("GET", pattern, handler)
}

// POST defines the method to add POST request
func (g *RouterGroup) POST(pattern string, handler HandlerFunc) {
	g.addRoute("POST", pattern, handler)
}
